﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;

namespace StoryMaker.Data
{
    public class XMLDataHandler<T>
    {
        public XMLDataHandler(Environment.SpecialFolder folderType, string fileName)
            : this(Environment.GetFolderPath(folderType), fileName)
        {
        }

        public XMLDataHandler(string fullPath)
            : this(Path.GetDirectoryName(fullPath), Path.GetFileName(fullPath))
        {
        }

        public XMLDataHandler(string folderLocation, string fileName)
        {
            if (Path.GetInvalidPathChars().Any(x => folderLocation.Contains(x)))
            {
                throw new ArgumentException("The given folder location contains invalid characters.  Folder name was " + folderLocation);
            }
            if (Path.GetInvalidFileNameChars().Any(x => fileName.Contains(x)))
            {
                throw new ArgumentException("The given file name contains invalid characters.  File name was " + fileName);
            }
            _folderLocation = folderLocation;
            this.fileName = fileName;
            serializer = new XmlSerializer(typeof(T));
        }

        private XmlSerializer serializer;

        private string _folderLocation;
        private string FolderLocation
        {
            get
            {
                if (!Directory.Exists(_folderLocation))
                {
                    Directory.CreateDirectory(_folderLocation);
                }
                return _folderLocation;
            }
        }

        private string fileName { get; set; }

        public void SaveData(T data)
        {
            string path = Path.Combine(_folderLocation, fileName);
            if (File.Exists(path))
            {
                File.Delete(path);
            }
            using (FileStream stream = new FileStream(Path.Combine(_folderLocation, fileName), FileMode.OpenOrCreate))
            {
                serializer.Serialize(stream, data);
            }
        }

        public T LoadData()
        {
            string path = Path.Combine(_folderLocation, fileName);
            if (File.Exists(path))
            {
                using (FileStream stream = new FileStream(path, FileMode.OpenOrCreate))
                {
                    return (T)serializer.Deserialize(stream);
                }
            }
            throw new FileNotFoundException("Path not found: " + path);
        }

    }
}
